package mobi.hami.huapin.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import mobi.hami.huapin.dao.ProductMapper;
import mobi.hami.huapin.dto.PageDTO;
import mobi.hami.huapin.model.Product;
import mobi.hami.huapin.model.ProductExample;
import mobi.hami.huapin.model.base.PageVO;
import mobi.hami.huapin.service.ProductService;
import mobi.hami.huapin.util.CommonPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 类说明
 *
 * @author 阿飞 jijunjian@hami.mobi
 * @date 2018/8/16 16:47
 */
@Service
public class ProductServiceImpl implements ProductService {

    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    private ProductMapper productMapper;

    /**
     * 修改商品状态
     *
     * @param product
     * @return
     */
    public int updateDelete(Product product) {

        return productMapper.updateDelete(product);
    }

    /**
     * 保存商品
     *
     * @param product
     * @return
     */
    @Override
    public int save(Product product) {
        return productMapper.insertSelective(product);
    }

    /**
     * 更新商品
     *
     * @param product
     * @return
     */
    @Override
    public int update(Product product) {


        return productMapper.updateByPrimaryKeySelective(product);

    }

    @Override
    public PageDTO<Product> getListPage(PageDTO page) {
        PageDTO<Product> pageDTO = new PageDTO<Product>();
        String sql = "SELECT COUNT(1) from  product where  " + page.getStr();
        int rs = jdbcTemplate.queryForObject(sql, null, Integer.class);
        String sqlstr = "SELECT * from  product where  " + page.getStr() + "  order by " + page.getOrder() + " desc  limit "
                + page.getPageindex() + "," + page.getPagesize();
        List<Product> users = jdbcTemplate.query(sqlstr, new RowMapper<Product>() {
            @Override
            public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
                Product user = new Product();
                user.setDeleted(rs.getInt("Deleted"));
                user.setId(rs.getLong("id"));
                user.setProduct_code(rs.getInt("Product_code"));
                user.setName(rs.getString("Name"));
                user.setFirst_sortid(rs.getInt("First_sortid"));
                user.setGmt_create(rs.getTime("Gmt_create"));
                user.setSecond_sortid(rs.getInt("Second_sortid"));
                user.setSubject_id(rs.getInt("subject_id"));
                user.setGmt_modified(rs.getTime("Gmt_modified"));
                user.setThird_sortid(rs.getInt("Third_sortid"));
                user.setOrder_num(rs.getInt("order_num"));
                return user;
            }
        });
        pageDTO.setData(users);
        pageDTO.setTotal(rs);
        return pageDTO;


    }

    /**
     * 更新商品
     *
     * @param spuid
     * @return
     */
    @Override
    public int delete(Long spuid) {

        Product product = new Product();
        product.setId(spuid);


        return productMapper.delete(product);
    }

    /**
     * 查询一个商品
     *
     * @param spuid
     * @return
     */
    @Override
    public Product getOney(Long spuid) {
        Product product = new Product();
        product.setId(spuid);
        return productMapper.selectOne(product);
    }

    /**
     * 测试商品
     *
     * @param subject_id
     * @return
     */
    @Override
    public List<Product> getTestList(int subject_id) {
        return productMapper.getTestList(subject_id);
    }

    /**
     * jdbtest
     *
     * @return
     */
    @Override
    public int jdbcTest() {

        String sql = "SELECT COUNT(1) from  product \n" +
                "   WHERE 1=1 and subject_id=9";

        int rs = jdbcTemplate.queryForObject(sql, null, Integer.class);

        return rs;

    }

    /**
     * 分页获取
     *
     * @param pageindex
     * @param pagesize
     * @param order
     * @param where
     * @return
     */
    @Override
    public PageVO<Product> getListBox(int pageindex, int pagesize, String order, String where) {
        String filed = " * ";
        String tablename = " product ";

        String pagesql = CommonPage.GetPageSql(tablename, "id", filed, pageindex, pagesize, order, where);


        List<Product> list = jdbcTemplate.query(pagesql, new RowMapper<Product>() {
            @Override
            public Product mapRow(ResultSet rs, int rowNum)
                    throws SQLException {
                //这里必须new对象，不能在方法外new，然后用同一个，因为是一个List，查询出来多个对象映射，
                //必须保证每一次调用都使用一个新的。
                //如果不new，而是使用同一个对象，会导致存入到List中的都是一样的对象（都是最后一个对象）。
                Product customer = new Product();
                customer.setName(rs.getString("name"));
                customer.setId(rs.getLong("id"));


                return customer;
            }
        });

        long totalcount = getCount(where);

        PageVO vo = PageVO.build(list);
        vo.setPages(pageindex);
        vo.setTotalCount(totalcount);
        vo.setPages(pagesize);

        return vo;
    }

    /**
     * 查询条数
     *
     * @param where
     * @return
     */
    @Override
    public int getCount(String where) {

        String sql = "SELECT COUNT(1) from  product \n" +
                "    WHERE 1=1 " + where;

        int rs = jdbcTemplate.queryForObject(sql, null, Integer.class);

        return rs;
    }


    @Override
    public PageVO<Product> getListBoxTest(int pageindex, int pagesize, String order, Map<String, Object> reqMap) {

        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();

        if (reqMap.containsKey("subject_id") && reqMap.get("subject_id").toString().length() > 0) {
            criteria.andSubject_idEqualTo(Integer.parseInt(reqMap.get("subject_id").toString()));
        }
        if (reqMap.containsKey("first_sortid") && reqMap.get("first_sortid").toString().length() > 0) {
            criteria.andFirst_sortidEqualTo(Integer.parseInt(reqMap.get("first_sortid").toString()));
        }
        if (reqMap.containsKey("name") && reqMap.get("name").toString().length() > 0) {
            criteria.andNameLike(reqMap.get("name").toString());
        }


        PageHelper.startPage(pageindex, pagesize);
        List<Product> list = productMapper.selectByExample(example);

        PageInfo<Product> pages = new PageInfo<>(list);


        PageVO vo = PageVO.build(list);
        vo.setPages(pageindex);
        vo.setTotalCount((long) (pages.getTotal()));
        vo.setPages(pagesize);

        //logger.info("条数",pages.getTotal());

        return vo;
    }

    /**
     * 查询条数
     *
     * @param reqMap
     * @return
     */
    @Override
    public int getCount(Map<String, Object> reqMap) {

        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        criteria.andSubject_idEqualTo(9);

        int count = productMapper.selectCountByExample(example);

        return count;
    }


    /**
     * mapper 分页面
     *
     * @param pageindex
     * @param pagesize
     * @param order
     * @return
     */
    public PageVO<Product> pageTest(int pageindex, int pagesize, String order, Product smarBoxCompanyDTO) {

        PageHelper.startPage(pageindex, pagesize);
        List<Product> list = productMapper.getPageTest(smarBoxCompanyDTO);

        PageInfo<Product> pages = new PageInfo<>(list);

        PageVO vo = PageVO.build(list);
        vo.setPages(pageindex);
        vo.setTotalCount((long) (pages.getTotal()));
        vo.setPages(pagesize);

        logger.info("条数" + pages.getTotal());

        return vo;
    }


}
